<template>
  <div class="dictionary">
    <div class="dictionary-header">
      <el-row>
        <el-col :span="1">
          <el-button
            type="primary"
            v-btnpermission="'btn-dicadd'"
            @click="addDialogVisible = true"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1">
          <!-- 导入 -->
          <el-upload
            class="upload"
            :multiple="false"
            :show-file-list="false"
            accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :http-request="toLead"
          >
            <template #trigger>
              <el-button v-btnpermission="'btn-dicload'" type="primary"
                >导入</el-button
              >
            </template>
          </el-upload>
        </el-col>
      </el-row>
      <el-card class="drug-head-contatiner-title2">
        <el-form :inline="true" :model="formSearch" class="demo-form-inline">
          <el-form-item label="名称" prop="Name">
            <el-input
              v-model="formSearch.Name"
              placeholder="请输入字典名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="分类">
            <el-select
              v-model="formSearch.TypeID"
              placeholder="--选择--"
              clearable
              filterable
            >
              <el-option
                v-for="item in dicTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="是否有效">
            <el-select v-model="formSearch.IsValid" placeholder="--选择--">
              <el-option
                v-for="item in isValidOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="dictionary-list">
      <el-row>
        <el-col>
          <!-- 角色列表 -->
          <el-table :data="DictionaryList" border stripe>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label="#"
              :index="indexMethod"
            ></el-table-column>
            <el-table-column prop="ID" label="编码"></el-table-column>
            <el-table-column prop="Name" label="名称"></el-table-column>
            <el-table-column prop="TypeIDName" label="分类"></el-table-column>
            <el-table-column prop="SN" label="顺序号"></el-table-column>
            <el-table-column prop="IsValid" label="是否有效">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.IsValid"
                  :active-value="1"
                  :inactive-value="0"
                  disabled
                />
              </template>
            </el-table-column>

            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  v-btnpermission="'btn-dicupdate'"
                  :icon="Edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  v-btnpermission="'btn-dicdelete'"
                  @click="rowDelete(scope.row.ID)"
                  :icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="8">
          <el-pagination
            background
            layout="total,prev, pager, next"
            v-model:total="formSearch.total"
            v-model:page-size="formSearch.pageSize"
            v-model:current-page="formSearch.page"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
      <el-dialog
        title="新增字典"
        v-model="addDialogVisible"
        width="40%"
        @close="addDislogClosed"
      >
        <el-form
          :model="addDialogForm"
          :rules="dictionaryFormRulesMixin.addFormRules"
          ref="addDialogRef"
          label-width="80px"
          inline
        >
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="编码" prop="ID">
                <el-input v-model="addDialogForm.ID" placeholder="请输入编码">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="字典名称" prop="Name">
                <el-input v-model="addDialogForm.Name" placeholder="--请选择--">
                </el-input> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item prop="TypeID" label="分类">
                <el-select
                  v-model="addDialogForm.TypeID"
                  placeholder="--选择--"
                >
                  <el-option
                    v-for="item in dicTypeOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="顺序号" prop="SN">
                <el-input-number
                  v-model="addDialogForm.SN"
                  placeholder="请输入顺序号"
                >
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item prop="IsValid" label="是否有效">
                <el-checkbox
                  v-model="addDialogForm.IsValid"
                  :true-label="1"
                  :false-label="0"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="上级编码" prop="ParentID">
                <el-input v-model="addDialogForm.ParentID" /> </el-form-item
            ></el-col>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addFormSubmit">确 定</el-button>
        </template>
      </el-dialog>
      <el-dialog
        title="编辑字典"
        v-model="editDialogVisible"
        @close="editDislogClosed"
        width="50%"
      >
        <el-form
          :model="editDialogForm"
          :rules="dictionaryFormRulesMixin.editFormRules"
          ref="editDialogRef"
          label-width="80px"
          inline
        >
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="编码" prop="ID">
                <el-input v-model="editDialogForm.ID" placeholder="请输入编码">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="字典名称" prop="Name">
                <el-input
                  v-model="editDialogForm.Name"
                  placeholder="--请选择--"
                >
                </el-input> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item prop="TypeID" label="分类">
                <el-select
                  v-model="editDialogForm.TypeID"
                  placeholder="--选择--"
                >
                  <el-option
                    v-for="item in dicTypeOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="顺序号" prop="SN">
                <el-input-number
                  v-model="editDialogForm.SN"
                  placeholder="请输入顺序号"
                >
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item prop="IsValid" label="是否有效">
                <el-checkbox
                  v-model="editDialogForm.IsValid"
                  :true-label="1"
                  :false-label="0"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="上级编码" prop="ParentID">
                <el-input v-model="editDialogForm.ParentID" /> </el-form-item
            ></el-col>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editFormSubmit">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount } from 'vue';
import { Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { dictionaryFormRulesMixin } from '@/utils/mixin';
import { importExcel } from '@/utils/excel';
import {
  getDictionaryList,
  addDictionary,
  editDictionary,
  delDictionary,
  AddDictionaryList,
} from '@/network/dictionaryTable';
import { getDictionaryType } from '@/network/dictionary';
//搜索
const formSearch = reactive({
  Name: '',
  TypeID: '',
  IsValid: 1,
  total: 0,
  page: 1,
  pageSize: 10,
});
//分页索引
const indexMethod = (index) => {
  return index + (formSearch.page - 1) * formSearch.pageSize + 1;
};
//导入Excel表格
const toLead = (e) => {
  importExcel.methods.importExcel(e, (res) => {
    if (res.length > 0) {
      AddDictionaryList(res).then(() => {
        ElMessage.success('导入成功');
        initDict();
        initData();
      });
    } else {
      ElMessage.error('请选择文件');
    }
  });
};
//初始化数据
const DictionaryList = ref([]);
const initData = () => {
  let params = {
    page: formSearch.page,
    pageSize: formSearch.pageSize,
    Name: formSearch.Name,
    TypeID: formSearch.TypeID,
    IsValid: formSearch.IsValid,
  };
  getDictionaryList(params).then((res) => {
    DictionaryList.value = res.data;
    formSearch.total = res.total;
  });
};
//初始化字典
const dicTypeOption = ref([]);
const isValidOption = ref([
  {
    value: 1,
    label: '有效',
  },
  {
    value: 0,
    label: '无效',
  },
]);

const initDict = async () => {
  await getDictionaryType().then((res) => {
    dicTypeOption.value = res;
  });
};
onBeforeMount(() => {
  initData();
  initDict();
});
//搜索
const onSubmit = () => {
  formSearch.page = 1;
  initData();
};
//重置
const onReset = () => {
  formSearch.Name = '';
  formSearch.TypeID = '';

  formSearch.page = 1;
  initData();
};
//分页
const handleCurrentChange = (val) => {
  formSearch.page = val;
  initData();
};
//新增
const addDialogVisible = ref(false);
const addDialogRef = ref(null);
const addDialogForm = reactive({
  ID: '',
  Name: '',
  TypeID: '',
  SN: null,
  IsValid: 1,
  ParentID: '',
});
const addFormSubmit = async () => {
  await addDialogRef.value.validate(async (valid) => {
    if (valid) {
      await addDictionary(addDialogForm)
        .then(() => {
          addDialogVisible.value = false;
          initData();
          initDict();
          ElMessage.success('新增成功');
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      ElMessage.error('请按要求填写');
      return false;
    }
  });
};
const addDislogClosed = () => {
  addDialogRef.value.resetFields();
  addDialogRef.value.clearValidate();
};
const editDislogClosed = () => {
  editDialogRef.value.resetFields();
  editDialogRef.value.clearValidate();
};
//编辑
const editDialogVisible = ref(false);
const editDialogRef = ref(null);
let editDialogForm = ref({
  ID: '',
  Name: '',
  TypeID: '',
  SN: null,
  IsValid: 1,
  ParentID: '',
});
const showEditDialog = (row) => {
  editDialogVisible.value = true;
  editDialogForm.value = JSON.parse(JSON.stringify(row));
};
// const editDislogClosed = () => {
//   editDialogForm.value = {};
// };
const editFormSubmit = async () => {
  await editDialogRef.value.validate(async (valid) => {
    if (valid) {
      await editDictionary(editDialogForm.value)
        .then(() => {
          editDialogVisible.value = false;
          initData();
          // initDict();
          ElMessage.success('编辑成功');
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      ElMessage.error('请按要求填写');
      return false;
    }
  });
};
//删除
const rowDelete = async (id) => {
  await ElMessageBox.confirm('确定删除该条记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async (action) => {
    if (action === 'confirm') {
      await delDictionary({ code: id })
        .then(() => {
          initData();
          // initDict();
          ElMessage.success('删除成功');
        })
        .catch((err) => {
          console.log(err);
          ElMessage.success('删除失败');
        });
    }
  });
};
</script>

<style lang="scss" scoped>
.dictionary {
  margin: 14px 15px 14px;
  .dictionary-header {
    .drug-head-contatiner-title2 {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }
  .dictionary-list {
    margin-top: 14px;
  }
}
</style>
